package cn.lefull.jpa.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpRequestUtil {
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }


    /**
     *
     * @description 查询员工信息
     * @author qijiang @email jiang1211@foxmail.com
     * @date 2018/11/16 下午3:24
     * @param [args]
     * @return void
     */
    public static void main(String[] args){
        String s=HttpRequestUtil.sendGet("https://oapi.dingtalk.com/user/listbypage", "access_token=e6ba6f36b45e373cb1cf652bfe513b2c&department_id=82028263&offset=0&size=100&order=entry_desc");
        JSONObject jsonObject =JSONObject.parseObject(s);
        System.out.println(jsonObject);
//       DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
//       OapiUserGetRequest request = new OapiUserGetRequest();
//       request.setUserid("zhangsan");
//       request.setHttpMethod("GET");
//       OapiUserGetResponse response = client.execute(request, "");

//       DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/listbypage");
//       OapiUserListbypageRequest request = new OapiUserListbypageRequest();
//       request.setDepartmentId(1L);
//       request.setOffset(0L);
//       request.setSize(10L);
//       request.setOrder("entry_desc");
//       request.setHttpMethod("GET");
//       client.execute(request,"");
//       OapiUserListbypageResponse execute = client.execute(request,"21");

//        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/listbypage");
//        OapiUserListbypageRequest request = new OapiUserListbypageRequest();
//        request.setDepartmentId(82028263L);
//        request.setOffset(0L);
//        request.setSize(10L);
//        request.setOrder("entry_desc");
//        request.setHttpMethod("GET");
//        try {
//            OapiUserListbypageResponse execute = client.execute(request,"e6ba6f36b45e373cb1cf652bfe513b2c");
//            System.out.println(execute.getUserlist());
//            System.out.println(execute.getUserlist());
//        }catch (Exception e){
//
//
//        }
    }
//查询部门信息
//    public static void main(String[] args){
//
//       // 发送 GET 请求
//        String s=HttpRequestUtil.sendGet("https://oapi.dingtalk.com/department/list", "access_token=cf3a07f3d27c3201a6f2ff813516f0f1\n");
//        JSONObject jsonObject =JSONObject.parseObject(s);
//        JSONArray departments = jsonObject.getJSONArray("department");
//        String department =" insert into department(id,createDeptGroup,name,parentid,autoAddUser" +
//                ",deptHiding,deptPermits,userPermits,outerPermitDepts,groupContainSubDept,deptManagerUseridList" +
//                ",errcode,outerPermitUsers,deptGroupChatId,department_order,outerDept,orgDeptOwner,errmsg) values ";
//        for (int i = 0; i < departments.size(); i++) {
//            Object o = departments.get(i);
//            JSONObject jsonObject1 = JSONObject.parseObject(JSON.toJSONString(o));
//            String param = "access_token=cf3a07f3d27c3201a6f2ff813516f0f1&id="+jsonObject1.getString("id");
//            String result=HttpRequestUtil.sendGet("https://oapi.dingtalk.com/department/get", param);
//            JSONObject jsonObjectResult =JSONObject.parseObject(result);
//
//            department+="("+jsonObjectResult.getString("id");
//            department+=","+jsonObject1.getInteger("createDeptGroup");
//            department+=","+"'"+jsonObject1.getString("name")+"'";
//            if(jsonObject1.containsKey("parentid")){
//            department+=","+jsonObject1.getString("parentid");
//            }else{
//            department+=","+-1;
//            }
//            department+=","+jsonObject1.getInteger("autoAddUser");
//            department+=","+jsonObjectResult.getInteger("deptHiding");
//            department+=","+"'"+jsonObjectResult.getString("deptPermits")+"'";
//            department+=","+"'"+jsonObjectResult.getString("userPermits")+"'";
//            department+=","+"'"+jsonObjectResult.getString("outerPermitDepts")+"'";
//            department+=","+jsonObjectResult.getInteger("groupContainSubDept");
//            department+=","+"'"+jsonObjectResult.getString("deptManagerUseridList")+"'";
//            department+=","+jsonObjectResult.getInteger("errcode");
//            department+=","+"'"+jsonObjectResult.getString("outerPermitUsers")+"'";
//            department+=","+"'"+jsonObjectResult.getString("deptGroupChatId")+"'";
//            department+=","+jsonObjectResult.getString("order");
//            department+=","+jsonObjectResult.getInteger("outerDept");
//            department+=","+"'"+jsonObjectResult.getString("orgDeptOwner")+"'";
//            department+=","+"'"+jsonObjectResult.getString("errmsg")+"'";
//            department+="),";
//            //insert into `user`(id,username) values(4,5),(5,6);
//        }
//            System.out.println(department.substring(0,department.length()-1));
//
////        //发送 POST 请求
////        String sr=HttpRequestUtil.sendPost("http://localhost:6144/Home/RequestPostString", "key=123&v=456");
////        System.out.println(sr);
//   }



}